package com.chendx.store.common.fastdfs;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xnf on 2022/3/30.
 */
@Component
public class FastDFSClientUtil {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {

        StorePath storePath = storageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                null);
        return storePath.getFullPath();
    }
    /**
     * 删除
     * @param filePath
     */
    public void delFile(String filePath){
        storageClient.deleteFile(filePath);
    }
    /**
     * 下载
     * @param groupName
     * @param path
     * @return
     */
    public byte[] download(String groupName, String path) throws IOException {
        InputStream inputStream = storageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>() {
            @Override
            public InputStream recv(InputStream inputStream) throws IOException {
                return inputStream;
            }
        });
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int len = 0;
        byte[] bytes = new byte[100];
        while ((len = inputStream.read(bytes,0,100))> 0){
            byteArrayOutputStream.write(bytes,0,len);
        }
        return byteArrayOutputStream.toByteArray();

    }
}
